package com.lecode.LRU;

import java.util.LinkedHashMap;

/**
 * Created by Administrator on 2020/8/15.
 * LRU:最近最久未使用
 */
public class LRUCache {

    /**缓存*/
    LinkedHashMap<Integer, Integer> cache;
    /**容量*/
    Integer cap;

    public Integer get(Integer key){
        if (!cache.containsKey(key)){
            return -1;
        }
        //将元素提到链表尾部
        makeRecently(key);
        return cache.get(key);
    }

    public void put(Integer key, Integer value){
        if (cache.containsKey(key)){
            cache.put(key, value);
            makeRecently(key);
            return;
        }
        /**容量已满：删除最久未使用的元素*/
        if (this.cap <= cache.size()){
            Integer next = cache.keySet().iterator().next();
            cache.remove(next);
        }
        cache.put(key,value);
    }


    public void makeRecently(Integer key){
        Integer value = cache.get(key);
        cache.remove(key);
        cache.put(key, value);
    }
}
